<script setup lang="ts">
import { watch, ref, markRaw, onMounted, onUnmounted } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import * as echarts from "echarts";
import { eqpTagLineChart } from "@/api/visual/visualConfig";
import dayjs from "dayjs";
defineOptions({
  name: "VChartLine"
});
const echartRef = ref();
let echartInstance: echarts.ECharts;
const isCollapsed = ref(false);
const props = withDefaults(
  defineProps<{
    propValue?: {
      contentList: Array<any>;
      title?: string;
      collapsed?: boolean;
      iconName?: string;
      option?: Record<string, any>;
    };
    element?: {
      style: {
        width?: number;
        height?: number;
        display?: string;
      };
    };
  }>(),
  {
    propValue: () => ({
      contentList: [],
      option: {},
      title: "",
      collapsed: false,
      iconName: "alert"
    }),
    element: () => ({ style: {} })
  }
);
const dataSelect = ref("");
let option: { grid: Record<string, any>; legend: Record<string, any>; xAxis: Record<string, any>; yAxis: Record<string, any>; series: any[] };
let yaxiMap: any[];
let seriesArr: any[];

//用于编辑器参数改变时响应变化
// watch(
//   () => props.element,
//   newVal => {
//     console.log(newVal);
//     renderChart(props.propValue.contentList);
//   },
//   { deep: true, immediate: true }
// );
watch(
  () => props.propValue.contentList,
  newVal => {
    renderChart(newVal as any);
  },
  { immediate: true }
);
onMounted(() => {
  echartInstance = markRaw(
    echarts.init(echartRef.value, undefined, {
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    })
  );
  echartInstance.on("legendselectchanged", (params: { name: string; selected: [] }) => {
    let { selected, name } = params;
    let isSelected = Object.keys(selected).filter(key => selected[key] === true);
    if (isSelected.length > 2) {
      params.selected[name] = false;
    }
    rednerRealChart(params.selected);
  });
});
onUnmounted(() => {
  echartInstance.off("legendselectchanged");
});
//真实渲染数据处理数据
function rednerRealChart(selected) {
  let isSelected = Object.keys(selected).filter(key => selected[key] === true);

  const [first, seconds] = isSelected;
  let firstData = seriesArr.find(item => item.name === first)?.data;
  let secoundData = seriesArr.find(item => item.name === seconds)?.data;
  if (firstData) firstData = deepCopy(firstData);
  if (secoundData) secoundData = deepCopy(secoundData);
  option.yAxis.forEach((el, i) => {
    el.min = 0;
    el.splitNumber = 5;
    if (first && el.name.indexOf(first) !== -1) {
      el.position = "left";
      el.show = true;
      const { max } = findMinMax(firstData);

      el.max = max;
      el.interval = Math.ceil(max / 5);
    } else if (seconds && el.name.indexOf(seconds) !== -1) {
      el.position = "right";
      el.show = true;
      const { max } = findMinMax(secoundData);

      el.max = max;
      el.interval = Math.ceil(max / 5);
    } else {
      delete el.position;
      el.show = false;
    }
  });

  option.series.forEach(el => {
    if (first && el.name.indexOf(first) !== -1) {
      el.data = firstData;
    } else if (seconds && el.name.indexOf(seconds) !== -1) {
      el.data = secoundData;
    } else {
      el.data = [];
    }
  });

  option.legend.selected = selected;
  if (echartInstance && echartInstance.resize) {
    echartInstance.resize({
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    });

    // 配置参数
    echartInstance.clear();
    echartInstance.setOption(option, true);
    console.log(option);
  }
}
function dateChange() {
  renderChart(props.propValue.contentList);
}
const disabledDate = (time: Date) => {
  const currentTime = new Date();
  return time.getTime() > currentTime.getTime();
};
function getOneHourBefore(dateTimeStr) {
  const dateTime = dayjs(dateTimeStr, "YYYY-MM-DD HH:mm:ss");
  const oneHourBefore = dateTime.subtract(1, "hour");
  return oneHourBefore.format("YYYY-MM-DD HH:mm:ss");
}
//数据初始化加接口请求
async function renderChart(newVal = []) {
  if (!newVal || newVal.length === 0) return;

  option = deepCopy(props.propValue.option);
  let data = deepCopy(newVal);
  let tagNums = extractValuesByKey(data, "tagNum");
  let [endTime, startTime] = getCurrentTimeAndAdjustedTime();
  if (dataSelect.value && dataSelect.value !== "") {
    endTime = dataSelect.value;
    startTime = getOneHourBefore(endTime);
  } else {
    dataSelect.value = endTime;
  }

  // let params = {
  //   // tagNums: ["TAG_FAC00059", "TAG_FAC00058"],
  //   tagNums,
  //   // startTime: "2024-07-24 13:30:00",
  //   // endTime: " 2024-07-24 14:00:00"
  //   startTime,
  //   endTime
  // };

  let rawData = await eqpTagLineChart({ tagNums, startTime, endTime });
  // let rawData = await eqpTagLineChart(params);
  let { xaxis, yaxis } = rawData;
  let legendData = extractValuesByKey(yaxis, "name");

  try {
    option.grid = {
      top: "20%",
      bottom: "20%"
    };
    option.legend.data = legendData;
    if (!legendData || legendData.length === 0) return;
    const selected = legendData.reduce((pre, cur, curI) => {
      let res = {
        [cur]: curI === 0 || curI === 1 ? true : false,
        ...pre
      };
      return res;
    }, {});
    option.xAxis.data = deepCopy(xaxis);
    option.xAxis.axisLabel = {
      interval: 13,
      formatter: function (value) {
        return value.split(" ").join("\n\n");
      }
    };
    yaxiMap = yaxis.map((item, index) => {
      const { name, unit } = item;
      return {
        type: "value",
        name: `${name}(${unit})`,
        show: index > 1 ? false : true,
        position: index === 0 ? "left" : "right"
      };
    });
    option.yAxis = deepCopy(yaxiMap);
    seriesArr = yaxis.map((item, index) => {
      const { name, data } = item;
      return {
        name,
        type: "line",
        symbol: "react",
        yAxisIndex: index,
        data
      };
    });
    option.series = deepCopy(seriesArr);

    rednerRealChart(selected);
    // 更新大小
  } catch (e) {
    console.error(e);
  }
}
function findMinMax(arr) {
  if (arr.length === 0) {
    return { min: null, max: null };
  }

  const min = Math.min(...arr);
  const max = Math.max(...arr);

  return { min, max: Math.ceil(max / 9.5) * 10 };
}
function extractValuesByKey(arr, key) {
  // 检查 arr 是否为数组
  if (!Array.isArray(arr)) {
    return [];
  }

  // 初始化结果数组
  const result = [];

  // 遍历数组对象
  for (const item of arr) {
    // 检查每个元素是否为对象且包含指定的键
    if (item && typeof item === "object" && key in item) {
      result.push(item[key]);
    }
  }

  // 返回结果数组
  return result;
}
function getCurrentTimeAndAdjustedTime(hours = 1) {
  // 获取当前时间
  const now = new Date();

  // 格式化时间为 "YYYY-MM-DD HH:MM:SS"
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 当前时间字符串
  const currentTime = formatDate(now);

  // 计算减去指定小时后的时间
  const adjustedTime = new Date(now.getTime() - hours * 60 * 60 * 1000);
  const adjustedTimeString = formatDate(adjustedTime);

  // 返回包含两个时间字符串的数组
  return [currentTime, adjustedTimeString];
}

function deepCopy(data) {
  try {
    return JSON.parse(JSON.stringify(data));
  } catch (error) {
    console.error(error);
    return {};
  }
}
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" :has-collapsed="propValue.collapsed">
    <div class="w-[100%] h-[100%] pt-[5px]">
      <px-date-picker
        v-model="dataSelect"
        type="datetime"
        range-separator="至"
        start-placeholder="选择时间"
        :disabled-date="disabledDate"
        value-format="YYYY-MM-DD HH:mm:ss"
        format="YYYY-MM-DD HH:mm:ss"
        @change="dateChange"
      />
      <div ref="echartRef" />
    </div>
  </leftCompWrapper>
</template>

<!-- <style lang="scss" scoped></style> -->
